﻿using GameTools.Service.Nlog;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;

namespace GameTools.Views.Items
{
    public partial class LogViewerControl : UserControl
    {
        public ObservableCollection<LogItem> LogItems
        {
            get => (ObservableCollection<LogItem>)GetValue(LogItemsProperty);
            set => SetValue(LogItemsProperty, value);
        }

        public static readonly DependencyProperty LogItemsProperty =
            DependencyProperty.Register(nameof(LogItems),
                typeof(ObservableCollection<LogItem>),
                typeof(LogViewerControl),
                new PropertyMetadata(new ObservableCollection<LogItem>(), OnLogItemsChanged));

        public LogViewerControl()
        {
            InitializeComponent();
            SubscribeToCollectionChanged(LogItems);
        }

        private static void OnLogItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = (LogViewerControl)d;
            if (e.OldValue is ObservableCollection<LogItem> oldCollection)
            {
                oldCollection.CollectionChanged -= control.LogItems_CollectionChanged;
            }
            if (e.NewValue is ObservableCollection<LogItem> newCollection)
            {
                control.SubscribeToCollectionChanged(newCollection);
            }
        }

        private void SubscribeToCollectionChanged(ObservableCollection<LogItem> collection)
        {
            if (collection != null)
            {
                collection.CollectionChanged += LogItems_CollectionChanged;
            }
        }

        private void LogItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                Dispatcher.Invoke(() => LogScrollViewer.ScrollToBottom());
            }
        }
    }
}